package com.qts.crm.task;

import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import com.qts.crm.company.api.dto.CompanyDTOForCRM;
import com.qts.crm.company.api.model.Company;
import com.qts.crm.company.api.service.CompanyService;
import com.qts.crm.constant.CompanyConstant;
import com.qts.crm.dto.AuthenticationHistory;
import com.qts.crm.dto.ResultSupport;
import com.qts.crm.enums.CompanyIndustry;
import com.qts.crm.mate.api.service.IMateService;
import com.qts.crm.redis.Redis;
import com.qts.crm.util.OkHttpUtils;
import com.qtshe.core.domain.company.CRMCompanyDTO;
import com.qtshe.core.dubbo.ICompanyService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * 同步数据从bd到crm
 * Created by qucheng on 17/7/10.
 */
@Component
public class DataTransfer {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Redis redis;

    @DubboConsumer
    private ICompanyService icompanyService;

    @DubboConsumer(version = "1.0.0")
    private CompanyService companyService;

    @DubboConsumer(version = "1.0.0")
    private IMateService iMateService;

    @Value("${auditHistoryUrl}")
    private String auditHistoryUrl;


    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void bdToCrmData() {
        //1.redis取到key
        String redisKey = "app2crm_company_update_notification";
        Set<Object> keys = redis.hmGetKeys(redisKey);
        for (Object key : keys) {
            //如果id在crm里面存在,直接更新数据,如果id不存在于crm,判断名称是否存在,存在就删除,新增数据,如果不存在,直接新增
            if (key == null) return;
            Long companyId = Long.parseLong(key.toString());
            CRMCompanyDTO companyBDDTO = icompanyService.getCRMCompanyById(companyId);
            // 判断日期,7月3日之前的数据全部不管
            if (companyBDDTO == null || companyBDDTO.getCreated() == null || companyBDDTO.getCreated().before(getDate())) {
                redis.hmDel(redisKey, key);
                return;
            }
            CompanyDTOForCRM companyCRMDTO = new CompanyDTOForCRM();
            transferBD2CRM(companyBDDTO, companyCRMDTO);
            Company company = null;
            try {
                //查crm是否存在该记录
                if (companyCRMDTO.getType().equals(CompanyConstant.COMPANY_TYPE)) {
                    // 根据cid查询
                    Company companyById = companyService.selectCompanyByBDId(companyId);
                    if (companyById != null) {
                        company = companyById;
                    } else {
                        // 根据BD平台外键编号查询
                        Long crmCompanyId = companyBDDTO.getCrmCompanyId();
                        if (crmCompanyId != null && crmCompanyId > 0) {
                            Company companyParam = companyService.getCompanyById(crmCompanyId);
                            if (companyParam != null) {
                                company = companyParam;
                            }
                        }
                        // 根据公司名称查询
                        if (company == null) {
                            String companyName = companyCRMDTO.getName();
                            Company companyByName = companyService.selectCompanyByName(companyName);
                            if (companyByName != null) {
                                company = companyByName;
                            }
                        }
                    }
                } else {//如果是个人,查询本地是否存在
                    Company companyById = companyService.selectCompanyByBDId(companyId);
                    // 如果不为空
                    if (companyById != null) {
                        company = companyById;
                    }
                }

                if (company == null) {//如果不存在,根据审核条件插入
                    //insert company
                    if (companyCRMDTO.getType().equals(CompanyConstant.COMPANY_TYPE)) {
                        // 判断审核状态是否成功
                        if (companyCRMDTO.getAuthenticatedStatus().equals(CompanyConstant.AUDITED)) {
                            saveCompany(companyId, companyCRMDTO);
                        }
                    } else {
                        if (companyCRMDTO.getAuthenticatedStatus().equals(CompanyConstant.AUDITED) && companyBDDTO.getCompanyBondStatus().equals(CompanyConstant.PAY_SUCCESS)) {
                            saveCompany(companyId, companyCRMDTO);
                        }
                    }
                } else {
                    if (company.getAuthenticatedStatus().equals(CompanyConstant.NOT_AUDITED)) {//覆盖crm未提交的数据
                        //设置归属人信息
                        companyCRMDTO.setOrgId(company.getOrgId());
                        companyCRMDTO.setOwner(company.getOwner());
                        companyCRMDTO.setStatus(CompanyConstant.MY_SAE_CODE); //默认私海
                        companyCRMDTO.setCreator(company.getCreator());
                        companyCRMDTO.setCid(companyId);
                        companyCRMDTO.setId(company.getId());//根据crmId来update
                        if (companyService.updateCompanyDTO(companyCRMDTO)) {
                            saveAuthenticationHistory(companyBDDTO, companyCRMDTO, company);
                        } else {
                            logger.error("修改bd数据失败:id = " + company.getId());
                        }
                    } else {
                        if (companyService.updateAuthenticatedStatus(company.getId(), companyCRMDTO.getAuthenticatedStatus(), companyId, companyCRMDTO.getType())) {
                            saveAuthenticationHistory(companyBDDTO, companyCRMDTO, company);
                        } else {
                            logger.error("插入bd数据失败:id = " + company.getId());
                        }
                    }
                    if (companyCRMDTO.getType().equals(CompanyConstant.COMPANY_TYPE)) {
                        // 查询审核状态
                        if (!companyCRMDTO.getFrom().equals(CompanyConstant.QTSH_CRM_WEB) && companyCRMDTO.getAuthenticatedStatus().equals(CompanyConstant.AUDIT_REJECT)) {
                            // 公司信息逻辑删除
                            if (!companyService.deleteCompanyById(company.getId())) {
                                logger.error("插入bd数据失败:id = " + company.getId());
                            }
                        }
                    } else {
                        if (!companyCRMDTO.getAuthenticatedStatus().equals(CompanyConstant.AUDITED) || !companyBDDTO.getCompanyBondStatus().equals(CompanyConstant.PAY_SUCCESS)) {
                            // 个人信息逻辑删除
                            if (!companyService.deleteCompanyById(company.getId())) {
                                logger.error("插入bd数据失败:id = " + company.getId());
                            }
                        }
                    }
                }
                redis.hmDel(redisKey, key.toString());
            } catch (Exception e) {
                logger.error("同步更新bd数据异常,companyId:" + companyId);
            }
        }
    }

    private void saveCompany(Long companyId, CompanyDTOForCRM companyCRMDTO) {
        companyCRMDTO.setCid(companyId);
        companyCRMDTO.setCreator(0L);
        companyCRMDTO.setOwner(0L);
        companyCRMDTO.setStatus(1);//默认可分配
        companyCRMDTO.setOrgId(1L);//默认组织
        if (!companyService.saveCompanyDTO(companyCRMDTO)) {
            logger.error("插入bd数据失败:id = " + companyId);
        }
    }

    /**
     * 保存审核记录
     */
    private void saveAuthenticationHistory(CRMCompanyDTO companyBDDTO, CompanyDTOForCRM companyCRMDTO, Company company) {

        AuthenticationHistory authenticationHistory = new AuthenticationHistory();
        authenticationHistory.setCompanyId(company.getId());
        authenticationHistory.setStatus(companyCRMDTO.getAuthenticatedStatus());
        authenticationHistory.setCreator(company.getCreator());
        authenticationHistory.setAuthenticatorName(companyBDDTO.getAuthenticator());
        authenticationHistory.setResult(companyBDDTO.getResult());

        String url = auditHistoryUrl + "/crm/authenticationHistory/saveAuthenticationHistory";
        try {
            ResultSupport result = OkHttpUtils.postRequest(url, authenticationHistory);
            if (!result.getSuccess()) {
                logger.error("保存审核记录失败");
            }
        } catch (IOException e) {
            logger.error("调用保存审核记录接口失败");
        }
    }


    private void transferBD2CRM(CRMCompanyDTO crmBDCompanyDTO, CompanyDTOForCRM companyDTO) {
        companyDTO.setId(crmBDCompanyDTO.getId());
        String companyName = crmBDCompanyDTO.getName();
        companyDTO.setName(companyName == null ? "" : companyName.replace("(", "（").replace(")", "）"));
        companyDTO.setType(getIntType(crmBDCompanyDTO.getCompanyType()));
        companyDTO.setCode(crmBDCompanyDTO.getCode());
        //审核状态
        companyDTO.setAuthenticatedStatus(getIntAuthenticatedStatus(crmBDCompanyDTO.getAuthenticatedStatus()));
        companyDTO.setAuthenticated(crmBDCompanyDTO.getAuthenticated());
        // 图片处理 七牛前缀 http://7xiyzg.com2.z0.glb.qiniucdn.com/
        String prefix = "http://7xiyzg.com2.z0.glb.qiniucdn.com/";
        String logo = crmBDCompanyDTO.getLogo();
        String businessLicence = crmBDCompanyDTO.getBusinessLicence();
        String identityCard = crmBDCompanyDTO.getIdentityCard();
        if (StringUtils.isNotEmpty(logo)) {
            companyDTO.setLogo(prefix + logo);
        }
        if (StringUtils.isNotEmpty(businessLicence)) {
            companyDTO.setLicenseImage(prefix + businessLicence);
        }
        if (StringUtils.isNotEmpty(identityCard)) {
            companyDTO.setIdCardImage(prefix + identityCard);
        }
        Long provinceId = crmBDCompanyDTO.getProvinceId();
        Long townId = crmBDCompanyDTO.getTownId();
        Long areaId = crmBDCompanyDTO.getAreaId();
        companyDTO.setProvinceId(provinceId != null ? provinceId.intValue() : null);
        companyDTO.setTownId(townId != null ? townId.intValue() : null);
        companyDTO.setAreaId(areaId != null ? areaId.intValue() : null);
        companyDTO.setAddress(crmBDCompanyDTO.getAddress());
        companyDTO.setAccountMobile(crmBDCompanyDTO.getAccountMobile());
        companyDTO.setIndustry(getIntIndustry(crmBDCompanyDTO.getIndustry()));//类型
        companyDTO.setManager(crmBDCompanyDTO.getCharger());
        companyDTO.setPosition(crmBDCompanyDTO.getPosition());
        companyDTO.setEmail(crmBDCompanyDTO.getEmail());
        companyDTO.setMobile(crmBDCompanyDTO.getMobile());
        companyDTO.setTel(crmBDCompanyDTO.getTelephone());
        companyDTO.setIntro(crmBDCompanyDTO.getIntro());

        companyDTO.setQq(crmBDCompanyDTO.getQq());
        companyDTO.setFrom(getIntFrom(crmBDCompanyDTO.getFrom()));
        companyDTO.setLongitude(crmBDCompanyDTO.getLongitude());
        companyDTO.setLatitude(crmBDCompanyDTO.getLatitude());
        companyDTO.setScale(getIntScale(crmBDCompanyDTO.getScale()));
        companyDTO.setApplyRefund(crmBDCompanyDTO.getApplyRefund());
        companyDTO.setThirdPartyId(crmBDCompanyDTO.getThirdPartyId());
        companyDTO.setBackgroundImage(crmBDCompanyDTO.getBackgroundImg());
        companyDTO.setInterviewAddress(crmBDCompanyDTO.getInterviewAddress());
        companyDTO.setBondMoney(crmBDCompanyDTO.getBondMoney() != null ? crmBDCompanyDTO.getBondMoney().doubleValue() : null);
        companyDTO.setPublishedPartjobs(crmBDCompanyDTO.getPublishedPartjobs());
        companyDTO.setPublishedPractices(crmBDCompanyDTO.getPublishedPractices());
        companyDTO.setCreated(crmBDCompanyDTO.getCreated());
    }


    /**
     * PERSONAL: 个人, ENTERPRISE: 企业, OPEN_OS: 开放平台, OTHER: 其他
     * @param type 类型
     * @return 返回值
     */
    private Integer getIntType(String type) {
        if (StringUtils.isEmpty(type)) return 0;
        if ("PERSONAL".equals(type)) return CompanyConstant.COMPANY_PERSONAL_TYPE;
        if ("ENTERPRISE".equals(type)) return CompanyConstant.COMPANY_TYPE;
        return 0;
    }


    private Integer getIntIndustry(String industryName) {
        Map<String, Integer> industry = new HashMap<>();
        for (CompanyIndustry industry1 : CompanyIndustry.values()) {
            industry.put(industry1.getValue(), industry1.getCode());
        }
        return industry.get(industryName);
    }

    /**
     * 来源 0未知 1 QTSHE_BD 2 QTSHE_COMPANY 3 QTSHE_IOS_COMPANY 4 QTSHE_ANDROID_COMPANY 5 QTSHE_WEB  6 QTSHE_THIRD_PARTY
     * @param from 类型
     * @return 返回值
     */
    private Integer getIntFrom(String from) {
        if (StringUtils.isEmpty(from)) return 0;
        if ("QTSH_CRM_WEB".equals(from)) return CompanyConstant.QTSH_CRM_WEB;
        if ("QTSHE_BD".equals(from)) return CompanyConstant.QTSHE_BD;
        if ("QTSHE_COMPANY".equals(from)) return CompanyConstant.QTSHE_COMPANY;
        if ("QTSHE_IOS_COMPANY".equals(from)) return CompanyConstant.QTSHE_IOS_COMPANY;
        if ("QTSHE_ANDROID_COMPANY".equals(from)) return CompanyConstant.QTSHE_ANDROID_COMPANY;
        if ("QTSHE_WEB".equals(from)) return CompanyConstant.QTSHE_WEB;
        if ("QTSHE_THIRD_PARTY".equals(from)) return CompanyConstant.QTSHE_THIRD_PARTY;
        return 0;
    }

    /**
     * 公司规模  	ONE: 1~20人, TWO: 20~50人, THREE: 50~100人, FOUR: 100~200人, FIVE: 200人以上;
     * @param scale 规模
     * @return int
     */
    private Integer getIntScale(String scale) {
        if (StringUtils.isEmpty(scale)) return 0;
        if ("ONE".equals(scale)) return 1;
        if ("TWO".equals(scale)) return 2;
        if ("THREE".equals(scale)) return 3;
        if ("FOUR".equals(scale)) return 4;
        if ("FIVE".equals(scale)) return 5;
        return 0;
    }

    /**
     * 审核状态 	NO_SUBMIT: 未提交审核, AUDITING: 审核中, AUDIT_SUCCESS: 审核成功, AUDIT_FAIL: 审核失败, OTHER: 其他
     * @param authenticatedStatus 审核状态
     * @return int
     */
    private Integer getIntAuthenticatedStatus(String authenticatedStatus) {
        if (StringUtils.isEmpty(authenticatedStatus)) return CompanyConstant.NOT_AUDITED;
        if ("NO_SUBMIT".equals(authenticatedStatus)) return CompanyConstant.NOT_AUDITED;
        if ("AUDITING".equals(authenticatedStatus)) return CompanyConstant.IN_AUDIT;
        if ("AUDIT_SUCCESS".equals(authenticatedStatus)) return CompanyConstant.AUDITED;
        if ("AUDIT_FAIL".equals(authenticatedStatus)) return CompanyConstant.AUDIT_REJECT;
        return CompanyConstant.NOT_AUDITED;
    }

    /**
     * 获取7月3号上线日期
     * @return 日期
     */
    private Date getDate() {
        // 7月3号时间戳
        long time = 1499011200000L;
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        return cal.getTime();
    }

}
